package com.nforce.linremote.converters;

import java.net.InetAddress;
import java.net.UnknownHostException;

import android.util.Log;

import com.nforce.linremote.Constants;

public class IpUtils {

	public static InetAddress convertIpToInetAddress(int ip) {
		InetAddress inetAddress = null;
		byte[] addressBytes = { (byte) (0xff & ip), (byte) (0xff & (ip >> 8)),
				(byte) (0xff & (ip >> 16)), (byte) (0xff & (ip >> 24)) };

		try {
			inetAddress = InetAddress.getByAddress(addressBytes);
		} catch (UnknownHostException e) {
			Log.e(Constants.DEBUG_TAG, "UnknownHostException");
		}
		return inetAddress;
	}

	public static byte[] convertIp(int ip) {
		return convertIpToInetAddress(ip).getAddress();
	}

	public static String convertIpToString(int ip) {
		return convertIpToInetAddress(ip).getHostAddress();
	}

	public static int convertIp(byte ip[]) {
		if (ip.length != 4) {
			throw new IllegalArgumentException("Not an IPv4 address");
		}
		return ((ip[3] & 0xff) << 24) | ((ip[2] & 0xff) << 16)
				| ((ip[1] & 0xff) << 8) | (ip[0] & 0xff);
	}

	public static String convertIpToString(byte ip[]) {
		String resultIp = "";
		try {
			resultIp = InetAddress.getByAddress(ip).getHostAddress();
		} catch (UnknownHostException e) {
			Log.e(Constants.DEBUG_TAG, "UnknownHostException");
		}
		return resultIp;
	}
}
